package itbour.onetouchshow.activity.version1_4;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.lsjr.net.AppNetConfig;
import com.lsjr.net.Encrypt;
import com.lsjr.utils.NetUtils;
import com.three.share.listener.ShareListener;
import com.umeng.analytics.MobclickAgent;
import com.utils.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_2.CommoninchingVideoBgActivity;
import itbour.onetouchshow.activity.version1_2.V1_2_VideoPreviewActivity;
import itbour.onetouchshow.activity.version1_3.VideoCoverActivity;
import itbour.onetouchshow.activity.version1_6.MakeActivityV1_6;
import itbour.onetouchshow.activity.video.videobg.VideobgDialgActivity;
import itbour.onetouchshow.activity.video.videopreview.VideoPreviewPresenter;
import itbour.onetouchshow.activity.web.CommWebActivity;
import itbour.onetouchshow.activity.web.CreateOrderActivity;
import itbour.onetouchshow.adapter.ButtonItemAdapter;
import itbour.onetouchshow.base.IntentCode;
import itbour.onetouchshow.bean.DownloadVideoBean;
import itbour.onetouchshow.bean.HomeDetailslBean;
import itbour.onetouchshow.bean.JsShareBean;
import itbour.onetouchshow.bean.V1_4DocPreviewBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.DataCreater;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.listener.OnMultiClickListener;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.listener.SoftKeyBoardListener;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.OnMultiClickUtils;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.ThirdAppInstall;
import itbour.onetouchshow.utils.TypeCastHelper;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;
import itbour.onetouchshow.utils.video.MakeProductContrl;
import itbour.onetouchshow.widget.ChangeShareLinkStyleDialogFragment;
import itbour.onetouchshow.widget.UserProductShareDialogFragment;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
@SuppressLint("ValidFragment")
public class V1_4_VideoPreviewActivity extends V1_2_VideoPreviewActivity implements View.OnClickListener {


    /**
     * 0待生成
     **/
    public static final int MAKE_PREPARING = 0;
    /**
     * 1生成中
     **/
    public static final int MAKE_MAKEING = 1;
    /**
     * 2生成失败
     **/
    public static final int MAKE_FAILE = 2;
    /**
     * 3生成成功
     **/
    public static final int MAKE_COMPLETED = 3;
    public static final int START_COMMWEBACTIVITY = 200;
    /**
     * 进度条的dialog
     */
    public OneToucDialog oneToucDialog;
    @BindView(R.id.id_ig_del_bg)
    protected ImageView ig_from;
    @BindView(R.id.id_tv_del)
    protected TextView tv_from;
    @BindView(R.id.ly_removewater)
    protected FrameLayout ly_removewater;
    @BindView(R.id.ly_videoframe)
    protected LinearLayout ly_videoframe;
    @BindView(R.id.ly_registrationform)
    protected LinearLayout ly_registrationform;
    @BindView(R.id.ig_videoframe_bg)
    protected ImageView ig_videoframe_bg;
    @BindView(R.id.ig_removewater)
    protected ImageView ig_removewater;
    @BindView(R.id.tv_removewater)
    protected TextView tv_removewater;

    @BindView(R.id.fl_xiumi_count)
    protected FrameLayout fl_xiumi_count;

    @BindView(R.id.tv_xiumi_count)
    protected TextView tv_xiumi_count;
    @BindView(R.id.tv_videoframe_bg)
    protected TextView tv_videoframe_bg;
    @BindView(R.id.lg_registrationform)
    protected ImageView lgRegistrationform;
    protected Handler handler = UIUtils.getHandler();
    protected Runnable runnable;
    protected V1_4DocPreviewBean docPreviewBean;
    protected V1_4DocPreviewBean.DocInfoBean docInfo;
    protected V1_4DocPreviewBean.PreviewInfoBean.CurrentBgBean currentBg = null;
    protected V1_4DocPreviewBean.PreviewInfoBean.VideoBean video = null;
    protected MakeProductContrl makeProductContrl;
    protected int MAKE_WORK_STATE = MakeProductContrl.MAKE_COMPLETED;
    /**
     * 选择视频状态
     */
    protected int downloadType = 2;//原视频
    @BindView(R.id.id_ig_chage_bg)
    ImageView chageIcon;
    /**
     * 1   现金支付 2积分支付
     */
    private int DefaultPayType = 0;
    private int dialogWidth = UIUtils.WHD()[0] / 100 * 65;

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        //super.afterCreate(savedInstanceState);
        getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            docId = extras.getString(AppConst.DOCID);
            subType = extras.getString(WorkPlatform.TYPE);
        }
        if (subType != null) {
            if (subType.equals(WorkPlatform.W0RK)) {
                //作品进来不显示背景推荐
                ryRecommended.setVisibility(View.GONE);
                menu.setVisibility(View.GONE);
            }
        }
        baseInit();
        //super.afterCreate(savedInstanceState);
        mPresenter = new VideoPreviewPresenter(this);
        EventBus.getDefault().register(this);
        registerExitReceiver();
        initOnClickListener();
        mPresenter.setV1_4_videoPreviewActivity(this);
        mPresenter.newLoadDocPreview(docId);

    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("作品预览");
        if (subType != null && subType.equals(WorkPlatform.W0RK)) {
            //个任务中心跳转逻辑
            getToolBarView().getRightTextView().setText("修改");
            up_product_edit.setEnabled(false);
            up_product_edit.setBackground(null);
            up_product_edit.onDrawClean();
        } else {
            getToolBarView().getRightTextView().setText("完成");
        }


        getToolBarView().getRightTextView().setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if (subType != null && subType.equals(WorkPlatform.W0RK)) {
                    if (docInfo.getWatermark() == 1) {
                        mPresenter.getDocString(docInfo.getId() + "");
                    } else {
                        //如果已经去水印  重新拷贝生成
                        setUserMakeTag(UserMakeTag.UPDATE);
                        showUpdateWorkDialog();
                    }
                } else {
                    sendRemoveThreeLogic();
                }
            }
        });
        //getToolBarView().getRightTextView().setOnClickListener(this);

    }

    /**
     * 去封面页面
     */
    protected void gotoCoverActivity() {
        Intent intent = new Intent(V1_4_VideoPreviewActivity.this, VideoCoverActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(AppConst.VIDEOURL, video.getVideoUrl());
        bundle.putString("docId", docInfo.getId() + "");
        bundle.putDouble(AppConst.VIDEOW, video.getW());
        bundle.putDouble(AppConst.VIDEOH, video.getH());
        bundle.putBoolean(AppConst.ISHAVECOVER, ishaveCover);
        bundle.putBoolean("islocalhost", false);
        bundle.putDouble("duration", video.getDuration() * 1000);
        if (ishaveCover) {
            bundle.putDouble("coverDuration", video.getCoverInfo().getCoverDuration());
        }
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    protected void initView() {
        super.initView();
        ly_registrationform.setOnClickListener(this);
        ly_videoframe.setOnClickListener(this);
        if (isShowCoverView) {
            //隐藏作品名称  减去50dp
            // isCleanTopMargin = UIUtils.dp2px(130 + 20 );
            isCleanTopMargin = 0;
        } else {
            lyCover.setVisibility(View.GONE);
            //  isCleanTopMargin = UIUtils.dp2px(130 + 20 - 50 - 20 - 15);
            isCleanTopMargin = 0;
        }
        imageViewbg.setImageResource(0);
        ig_from.setImageResource(0);
        edTvbg.setText("广告边框");
        tv_from.setText("报名表单");


        tvProductTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(V1_4_VideoPreviewActivity.this, "c2_product_remove_wm_click");
                if (TypeCastHelper.toInt(App.getIntegral() * 0.01) >= (docInfo.getWatermarkPts() * 0.01)) {
                    //如果休米足够直接购买
                    showPayModuleSelect(-1, 0);
                } else {
                    showPayModuleSelect(0, 1);
                }

            }
        });

        ly_removewater.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                MobclickAgent.onEvent(V1_4_VideoPreviewActivity.this, "c2_product_remove_wm_click");
                if (TypeCastHelper.toInt(App.getIntegral() * 0.01) >= (docInfo.getWatermarkPts() * 0.01)) {
                    //如果休米足够直接购买
                    showPayModuleSelect(-1, 0);
                } else {
                    showPayModuleSelect(0, 1);
                }
            }
        });

        idLyuserMake.setOnClickListener(null);

        //下载至本地
        tvSaveToLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentBg == null) {
                    showNewDialog();
                } else {
                    showDownloadType();
                }
            }
        });

        //分享
        tvShareToOther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ThirdAppInstall.cheackThirdPartIsInstall(getViewContext());
                if (ThirdAppInstall.isOnePartInstall()) {
//                if (ThirdAppInstall.isAvailableOne(getApplicationContext())) {
//                    StartThirdAppDialog startThirdAppDialog = new StartThirdAppDialog();
//                    startThirdAppDialog.show(getFragmentManager(), "startThirdAppDialog");
                    showShareDialog();
                } else {
                    T_.showCustomToast("请安装微信或QQ或微博~");
                }
            }
        });
        chageIcon.setImageResource(R.mipmap.video_icon_add);
        ig_from.setImageResource(R.mipmap.video_icon_add);
    }

    //修改了分享样式
    private void showShareDialog() {
        UserProductShareDialogFragment productShareDialog = new UserProductShareDialogFragment(ChangeShareLinkStyleDialogFragment.DialogType.TYPEOFCUSTOMAPP);
        JsShareBean jsShareBean = new JsShareBean();
        String shareTitle = PreferencesHelper.getData(AppConst.KEY_APP_SHARE_TITLE);
        String shareContent = PreferencesHelper.getData(AppConst.KEY_APP_SHARE_CONTENT);
        HomeDetailslBean basicInfo = new Gson().fromJson(SpUtils.getInstance().getString(AppConst.APPBASEINFO), HomeDetailslBean.class);
        if (TextUtils.isEmpty(shareTitle) && basicInfo != null && basicInfo.getAppControl() != null) {
            shareTitle = basicInfo.getAppControl().getVideoShareTitle();
        }
        if (TextUtils.isEmpty(shareContent) && basicInfo != null && basicInfo.getAppControl() != null) {
            shareContent = basicInfo.getAppControl().getVideoShareMsg();
        }
        jsShareBean.setTitle(shareTitle);
        jsShareBean.setContent(shareContent);
        if (video != null && video.getCoverInfo() != null) {
            if (!TextUtils.isEmpty(video.getCoverInfo().getCover())) {
                jsShareBean.setThumb(video.getCoverInfo().getCover());
            }
        } else {
            if (video.getThumbs() != null && video.getThumbs().size() > 0) {
                jsShareBean.setThumb(video.getThumbs().get(0));
            }
        }

        List<Long> list = new ArrayList<>();
        list.add(Long.valueOf(docId));
        list.add(Long.valueOf(App.getUserId()));
        String encrpty = Encrypt.shareCustomEncryptNumbers(list);
        String baseShareUrl = AppNetConfig.getInstance().getMbuider().getShareUrl();
        String shareUrl = baseShareUrl + encrpty;
        jsShareBean.setUrl(shareUrl);

        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                T_.showToastReal("分享成功");
            }

            @Override
            public void shareFailure(Exception e) {
                T_.showToastReal("分享失败" + e.getMessage());
            }

            @Override
            public void shareCancel() {
                T_.showToastReal("取消分享");
            }
        };
        //修改链接样式点击事件
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChangeShareLinkStyleDialogFragment styleDialogFragment = new ChangeShareLinkStyleDialogFragment(ChangeShareLinkStyleDialogFragment.DialogType.TYPEOFCUSTOMAPP);
                styleDialogFragment.onShow(V1_4_VideoPreviewActivity.this);
                styleDialogFragment.setOnDismissListener(new ChangeShareLinkStyleDialogFragment.onDismissListener() {
                    @Override
                    public void onDismiss() {
                        productShareDialog.updateTitleAndContent();
                    }
                });
            }
        };
        productShareDialog.setData(jsShareBean, shareListener, onClickListener);
        productShareDialog.onShow(V1_4_VideoPreviewActivity.this);
    }

    public void showDownloadType() {
        /**
         * 默认弹框就是原视频
         */
        downloadType = 2;
        //  final ButtonItemAdapter adapter = new ButtonItemAdapter(this, R.array.socialNetworks);
        int width = UIUtils.WHD()[0] / 100 * 65;
        List<String> mList = new ArrayList<>();
        mList.add("原视频");
        mList.add("原视频(带边框)");
        final ButtonItemAdapter adapter = new ButtonItemAdapter(mList);
        //adapter.setItemPositionEnabled(0);
        adapter.setmSelectedPos(0);
        adapter.setCallbacks(new ButtonItemAdapter.ItemCallback() {
            @Override
            public void onItemClicked(int itemIndex) {
                if (itemIndex == 0) {
                    downloadType = 2;
                } else {
                    downloadType = 1;
                }
            }
        }, new ButtonItemAdapter.ButtonCallback() {
            @Override
            public void onButtonClicked(int buttonIndex) {
            }
        });
        new OneToucDialog.Builder(this).
                title("选择要保存的视频").adapter(adapter, null)
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                // L_.e("下载的类型" + downloadType);
                showNewDialog();


            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
            }
        }).cancelable(false).setmWidth(width).show();
    }

    /**
     * 禁用项  和默认项
     *
     * @param positionEnabled
     * @param defaultSelect
     */

    public void showPayModuleSelect(int positionEnabled, int defaultSelect) {
        //  final ButtonItemAdapter adapter = new ButtonItemAdapter(this, R.array.socialNetworks);
        List<String> mList = new ArrayList<>();
        final ButtonItemAdapter adapter = new ButtonItemAdapter(mList);
        if (positionEnabled != -1) {
            adapter.setItemPositionEnabled(positionEnabled);
            mList.add("秀米支付   <font color='#16cacb'><small>(最低一折起)</small></font>");
        } else {
            mList.add("秀米支付" /*+ "(" + docInfo.getWatermarkFee() + ")"*/);
        }
        mList.add("在线支付  " + "(" + String.format("%.2f", docInfo.getWatermarkFee() * 0.01) + "元)");
        if (defaultSelect != -1) {
            adapter.setmSelectedPos(defaultSelect);
            seletPayModule(defaultSelect);
        }
        adapter.setCallbacks(new ButtonItemAdapter.ItemCallback() {
            @Override
            public void onItemClicked(int itemIndex) {
                seletPayModule(itemIndex);
                if (positionEnabled != -1 && itemIndex == 0) {
                    oneToucDialog.dismiss();
                    Bundle bundle = new Bundle();
                    bundle.putString(AppConst.WEBTYPE, AppConst.COMWEB_XIUMI);
                    openActivity(CommWebActivity.class, bundle);
                }

            }
        }, new ButtonItemAdapter.ButtonCallback() {
            @Override
            public void onButtonClicked(int buttonIndex) {
                seletPayModule(buttonIndex);
            }
        });
        oneToucDialog = new OneToucDialog.Builder(this).
                title("选择支付方式").adapter(adapter, null)
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        Log.e("TAH", "点击确定");
                        // showVipDialog();

                        if (NetUtils.isConnected(getApplication())) {
                            if (docInfo.getWatermark() == 1 && docInfo.getWatermarkPay() == 1) {
                                showProgressDialogWithText("正在努力去水印");
                                mPresenter.removeWatermark(docInfo.getId() + "");
                            } else {
                                // showRemoveWaterDialog();
                                if (oneToucDialog != null) {
                                    oneToucDialog.dismiss();
                                }
                                Bundle bundle = new Bundle();
                                bundle.putString("docId", docInfo.getId() + "");
                                bundle.putInt("defaultPayType", DefaultPayType);
                                openActivity(CreateOrderActivity.class, bundle);
                            }
                        } else {
                            T_.showCustomToast("请检查网络");
                        }

                    }
                })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        Log.e("TAH", "点击确定");
                    }
                }).cancelable(false).setmWidth(dialogWidth).show();
    }

    private void seletPayModule(int position) {
        if (position == 0) {
            //积分支付
            DefaultPayType = 2;
        } else {
            DefaultPayType = 1;
        }
    }


    /**
     * 作品生成失败所有不可点击状态
     */
    public void isWorkFaile() {
        editBg.setEnabled(false);
        delBg.setEnabled(false);
        tvSaveToLocal.setEnabled(false);
        tvSaveToLocal.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
        tvShareToOther.setEnabled(false);
        tvShareToOther.setTextColor(Color.parseColor("#666666"));
        tvShareToOther.setBackgroundResource(R.drawable.btn_share_gary_background);
        //imageViewbg.setAlpha((float) 0.5);
        Drawable leftDrawable = getResources().getDrawable(R.mipmap.icon_video_down_gary);
        leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
        tvSaveToLocal.setCompoundDrawablePadding(UIUtils.dip2px(3));
        tvSaveToLocal.setCompoundDrawables(leftDrawable, null, null, null);

        edTvbg.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
        tv_from.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
        up_product_edit.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));

        tvProductTag.setBackgroundResource(R.drawable.shape_un_tag_bg);
        tvProductTag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
        tvProductTag.setText("高清去水印");
        tvProductTag.setEnabled(false);

        up_product_edit.setEnabled(false);
        up_product_edit.setBackground(null);
        up_product_edit.onDrawClean();
        chageIcon.setAlpha((float) 0.5);
        ig_from.setAlpha((float) 0.5);
    }

    /**
     * 不是尊享会员弹出提示
     */
    public void showVipDialog() {
        new OneToucDialog.Builder(this)
                .content("该模板仅限尊享会员使用,开通尊享会员获取更多特权及服务")
                .positiveText("去查看").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(dialogWidth)
                .show();
    }

    @Override
    public void showAlertDialog(String context) {
        if (getUserMakeTag().equals(UserMakeTag.SETCOVER)) {
            context = "你已为此作品去水印，请重新生成作品后设置封面";
        } else if (getUserMakeTag().equals(UserMakeTag.SETBG)) {
            context = "你已为此作品去水印，请重新生成作品后设置边框";
        }
        new OneToucDialog.Builder(this)
                .content(context)
                .positiveText("重新生成").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                mPresenter.getCopyDocStringAndNew(docInfo.getId() + "");
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(dialogWidth)
                .show();

    }

    public void showNewDialog() {
        requestPermission(new PermissionListener() {
            @Override
            public void onGranted() {
                OneToucDialog.Builder builder = new OneToucDialog.Builder(V1_4_VideoPreviewActivity.this);
                if (getState().equals(UserMakeTag.SHOW)) {
                    builder.content("正在生成预览");
                } else {
                    builder.content("正在下载");
                }
                oneToucDialog = builder.neutralText("取消").onNeutral(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        // OneToucDialog.startQuickProgressTimer(finalOneToucDialog);
                        if (mPresenter != null && mPresenter.task != null) {
                            mPresenter.task.cancel();
                        }
                    }
                }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE_DOWNLOAD)
                        .cancelable(false).setShowDownloadProgress(true).setmWidth(dialogWidth)
                        .show();

                mPresenter.downLoadForAliOss(docInfo.getId() + "", downloadType);
            }

            @Override
            public void onDenied(List<String> list) {
            }
        }, Permission.Group.STORAGE);
    }

    /**
     * 非wifi情况下下载耗流量提示框
     */
    public void showflowDialog(int maxSize, String url) {
        new OneToucDialog.Builder(this)
                .content("处于非wifi网络,继续保存会消耗流量，文件大小约" + maxSize / 1000 + "M")
                .positiveText("继续保存").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                mPresenter.alidownLoadFile(url);
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(dialogWidth)
                .show();
    }

    @Override
    public void loadFaild(String error) {
        //super.loadFaild(error);
        //只要返回失败都下载弹框消失
        try {
            if (oneToucDialog != null && oneToucDialog.isShowing()) {
                oneToucDialog.dismiss();
            }
            if (makeProductContrl == null && makeProductContrl.oneToucDialog != null &&
                    makeProductContrl.oneToucDialog.isShowing()) {
                makeProductContrl.oneToucDialog.dismiss();
            }
        } catch (Exception e) {

        }


    }

    /**
     * 去水印状态
     */

    @Override
    public void waterStatus() {
        if (docInfo == null) return;
        switch (docInfo.getWatermark()) {
            case 1:
                //已付款
                switch (docInfo.getWatermarkPay()) {
                    case 1:
                        //有水印 重新发起去水印
                        tvProductTag.setEnabled(true);
                        tvProductTag.setText("去水印");
                        //mPresenter.removeWatermark(docInfo.getId() + "");
                        break;
                    case 0:
                        tv_xiumi_count.setVisibility(View.VISIBLE);
                        fl_xiumi_count.setVisibility(View.VISIBLE);
                        tvProductTag.setEnabled(true);
                        //tvProductTag.setText("高清去水印" + "(" + String.format("%.2f", docInfo.getWatermarkPts() * 0.01) + "秀米)");
                        tvProductTag.setText("高清去水印" + "(" + TypeCastHelper.toInt(docInfo.getWatermarkPts() * 0.01) + "秀米)");
                        tv_xiumi_count.setText(TypeCastHelper.toInt(docInfo.getWatermarkPts() * 0.01) + "秀米");
                        break;
                }
                break;
            case 0:
                if (subType == null || !subType.equals(WorkPlatform.W0RK)) {
                    tv_videoframe_bg.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                    ly_videoframe.setEnabled(false);
                    ig_videoframe_bg.setImageResource(R.mipmap.icon_preview_bg_un);
                    ig_videoframe_bg.setAlpha((float) 0.5); //注意：透明度取值范围是0~125，0表示完全透明，然后一直递增
                }
                tv_xiumi_count.setVisibility(View.GONE);
                fl_xiumi_count.setVisibility(View.GONE);
                ly_removewater.setEnabled(false);
                tv_removewater.setText("已去水印");
                tv_removewater.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                ig_removewater.setImageResource(R.mipmap.icon_water);
                tvProductTag.setText("已去水印");
                tvProductTag.setBackgroundResource(R.drawable.shape_un_tag_bg);
                tvProductTag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                tvProductTag.setEnabled(false);
                ryRecommended.setVisibility(View.GONE);
                up_product_edit.setEnabled(false);
                up_product_edit.setBackground(null);
                up_product_edit.onDrawClean();
                if (getUserMakeTag().equals(UserMakeTag.REMOVEWATER)) {
                    edTvbg.setTextColor(UIUtils.getColor(R.color.tab_color_false));
                    imageViewbg.setAlpha((float) 0.5);
                    editBg.setEnabled(false);
                    tv_cover_settag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                    //不许点击封面
                    lyCover.setEnabled(false);
                    id_ig_more.setVisibility(View.GONE);
                    //id_tv_cover_tag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                    ig_video_rv.setAlpha((float) 0.5); //注意：透明度取值范围是0~125，0表示完全透明，然后一直递增
                }

                break;
        }

        switch (docInfo.getFormState()) {
            case 1:
                lgRegistrationform.setImageResource(R.mipmap.icon_baoming_bg);
                break;
            case 0:
                lgRegistrationform.setImageResource(R.mipmap.icon_baoming_bg_un);
                break;
        }
        if (docInfo.getGenerateStatus() == MAKE_FAILE) {
            tvProductTag.setEnabled(false);
        }
    }

    @SuppressLint("ValidFragment")
    public void showUpdateWorkDialog() {
        String context;
        if (getUserMakeTag().equals(UserMakeTag.SETCOVER)) {
            context = DataCreater.setCover;
            showAlertDialog(context);
        } else if (getUserMakeTag().equals(UserMakeTag.SETBG)) {
            context = DataCreater.setbg;
            showAlertDialog(context);
        } else {
            // context = "去水印后,修改作品将生成带水印新作品，去水印作品仍会保留";
            mPresenter.getCopyDocStringAndNew(docInfo.getId() + "");
        }

    }

    @Override
    public void getDownloadUrl(String result) {
        DownloadVideoBean downloadVideoBean = new Gson().fromJson(result, DownloadVideoBean.class);
        if (!NetUtils.isWifi(this) && TypeCastHelper.toInt(downloadVideoBean.getFileSize() / 1000) > 5) {
            showflowDialog(downloadVideoBean.getFileSize(), downloadVideoBean.getDownloadUrls().get(0));
        } else {
            mPresenter.alidownLoadFile(downloadVideoBean.getDownloadUrls().get(0));
        }
    }

    /**
     * 作品名称
     *
     * @param docInfo
     */
    public void setProductName(V1_4DocPreviewBean.DocInfoBean docInfo) {
        String docNm = docInfo.getDocNm();
        // 作品名称
        if (up_product_edit != null) {
            up_product_edit.setText(docNm);
            up_product_edit.setSingleLine();
        }

    }

    /**
     * 作品背景
     */
    protected void setProductBg(V1_4DocPreviewBean.PreviewInfoBean.CurrentBgBean currentBg, V1_4DocPreviewBean.PreviewInfoBean.VideoBean video
            , V1_4DocPreviewBean.PreviewInfoBean.CurrentBgBean.VideoFrameBean videoFrame) {
        if (currentBg == null) {
            isHaveBg = false;
            bgUrl = null;
            cleanBg(video);
            ig_videoframe_bg.setImageResource(R.mipmap.icon_preview_bg_un);
        } else {
            isHaveBg = true;
            bgUrl = currentBg.getThumbs().get(0);
            //有视频尺寸才设置背景
            if (videoFrame != null) {
                showRealSizeView(currentBg, videoFrame);
            }
            ig_videoframe_bg.setImageResource(R.mipmap.icon_preview_bg);
        }
    }

    public void setCoverInfo() {
        V1_4DocPreviewBean.PreviewInfoBean.VideoBean.CoverInfo coverInfo = video.getCoverInfo();
        /*封面*/
        if (coverInfo == null) {
            ig_video_rv.setVisibility(View.GONE);
            tv_cover_settag.setVisibility(View.VISIBLE);
            tv_cover_settag.setText("未设置");
            ishaveCover = false;
        } else {
            String cover = video.getCoverInfo().getCover();
            ishaveCover = true;
            if (!TextUtils.isEmpty(cover)) {
                ImageLoader.getInstance().showImage(this, cover, ig_video_rv);
                ImageLoader.getInstance().showImage(V1_4_VideoPreviewActivity.this, cover, controller.imageView());
            }
            tv_cover_settag.setVisibility(View.GONE);
            ig_video_rv.setVisibility(View.VISIBLE);
        }

    }

    public void showRealSizeView(V1_4DocPreviewBean.PreviewInfoBean.CurrentBgBean currentBg, V1_4DocPreviewBean.PreviewInfoBean.CurrentBgBean.VideoFrameBean videoFrame) {
        //docInfo.BgInfoBean.CurrentBgBean.ImageBean image = docInfo.getBgInfo().getCurrentBg().getImage();
        int w = (int) currentBg.getW();
        int h = (int) currentBg.getH();
        int x = (int) videoFrame.getX();
        int y = (int) Math.ceil(videoFrame.getY());
        int videoH = (int) videoFrame.getH();
        int[] whd = UIUtils.WHD();
        int visableW = whd[0];
        float scale = w * 1.0f / visableW;

        RelativeLayout.LayoutParams imgLp = (RelativeLayout.LayoutParams) idPrvBg.getLayoutParams();
        h = (int) (visableW * h * 1.0f / w);
        imgLp.width = visableW;
        imgLp.height = h;
        idPrvBg.setLayoutParams(imgLp);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        y = (int) Math.ceil(y * 1.0f / scale);
        x = (int) Math.ceil(x * 1.0f / scale);
        videoH = (int) (videoH * 1.0f / scale);
        lp.leftMargin = x;
        lp.topMargin = y + isCleanTopMargin;
        lp.height = videoH;
        int videoW = (int) (videoFrame.getW() * 1.0f / scale);
        lp.width = videoW;
        idVideoRy.setLayoutParams(lp);
        ImageLoader.getInstance().showImageNoplace(V1_4_VideoPreviewActivity.this, bgUrl, idPrvBg);
        RelativeLayout.LayoutParams lyCoverParams = (RelativeLayout.LayoutParams) lyCover.getLayoutParams();
        lyCoverParams.addRule(RelativeLayout.BELOW, R.id.id_ly_edit_content);// 子控件相对于控件：imageViewId在其的下面

        //在图片的上方
        RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) idPrvBgRy.getLayoutParams();
        layoutParams1.addRule(RelativeLayout.BELOW, R.id.id_ly_cover);// 子控件相对于控件：imageViewId在其的下面

        // idPrvBgRy.setLayoutParams(layoutParams1);
        editContent.setVisibility(View.GONE);
//        idLyuserMake.setVisibility(View.VISIBLE);
//        tvSaveShare.setVisibility(View.GONE);
//        tvSaveToLocal.setVisibility(View.VISIBLE);
    }

    public void showEdittextSetting() {
        //rwb：取消EditText焦点，并且隐藏输入法。
        SoftKeyBoardListener.setListener(V1_4_VideoPreviewActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                //L_.i("键盘隐藏 高度" + height);
                if (!TextUtils.isEmpty(up_product_edit.getText().toString()) && up_product_edit.getText().length() > 0) {
                    // mPresenter.deleteVideoBg(up_product_edit.getText().toString());
                    mPresenter.doReNameWork(docInfo.getId() + "", up_product_edit.getText().toString());
                }
                cleanEditTextFocus();
            }
        });
    }

    public void loadNewDocPreviewSuccess(String result) {
        L_.e(result);

        dismissProgressDialog();
        docPreviewBean = new Gson().fromJson(result, V1_4DocPreviewBean.class);
        docInfo = docPreviewBean.getDocInfo();
        // V1_4DocPreviewBean.ProgressInfoBean progressInfo = docPreviewBean.getProgressInfo();
        // int generateStatus = docInfo.getGenerateStatus();
        MakeProductContrl.instance().setInitialize(new MakeProductContrl.MakeProductListener() {

            @Override
            public void makeSuccess(String result) {
                makeOverProduct(result);
            }

            @Override
            public void makeFaile() {
                MAKE_WORK_STATE = MakeProductContrl.MAKE_FAILE;
                isWorkFaile();
                makeOverProduct(result);

            }

            @Override
            public void makeiing(String result) {

            }

            @Override
            public void lookLater() {
                sendRemoveThreeLogic();
            }

            @Override
            public void isDraft(String result) {

            }
        }, this, MakeProductContrl.SignalTag.SHOW_PROGRESS, UserMakeTag.REMOVEWATER);

        MakeProductContrl.instance().loadNewDocPreviewSuccess(result);
    }

    @Override
    public void downLoadVideoSuccess(String string) {
        dismissProgressDialog();
    }

    @Override
    public void saveAndShare() {

        requestPermission(new PermissionListener() {
            @Override
            public void onGranted() {
                // T_.showToastReal("成功");
                showProgressDialogWithText("正在下载...");
                mPresenter.getDownVideoUrl(docInfo.getId() + "");
            }

            @Override
            public void onDenied(List<String> list) {
                //T_.showToastReal("拒绝");
            }
        }, Permission.Group.STORAGE);

    }

    private void makeOverProduct(String result) {
        if (oneToucDialog != null) {
            oneToucDialog.dismiss();
        }

        docPreviewBean = new Gson().fromJson(result, V1_4DocPreviewBean.class);
        docInfo = docPreviewBean.getDocInfo();
        setProductName(docInfo);
        V1_4DocPreviewBean.PreviewInfoBean previewInfo = docPreviewBean.getPreviewInfo();

        if (previewInfo != null) {
            currentBg = previewInfo.getCurrentBg();
            video = previewInfo.getVideo();
        }
        V1_4DocPreviewBean.PreviewInfoBean.CurrentBgBean.VideoFrameBean videoFrame = null;
        if (currentBg != null) {
            videoFrame = currentBg.getVideoFrame();

        }
        setProductBg(currentBg, video, videoFrame);
        //setCoverInfo();

        menu.setVisibility(View.GONE);
        ryRecommended.setVisibility(View.GONE);
        contentLayout.setVisibility(View.VISIBLE);
        waterStatus();


        customVideoPlay.releasePlayer();
        customVideoPlay.start();
        onChageUrlStartPlay(video.getVideoUrl(), "");
        customVideoPlay.seekTo(10);
    }

    /*没有背景*/
    protected void cleanBg(V1_4DocPreviewBean.PreviewInfoBean.VideoBean video) {
        isCleanTopMargin = 0;
        idPrvBg.setImageResource(0);
        int videoH = (int) video.getH();
        int[] whd = UIUtils.WHD();
        int visableW = whd[0];
        float scale = (float) (video.getW() * 1.0f / visableW);
        videoH = (int) (videoH * 1.0f / scale);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        lp.leftMargin = 0;
        lp.topMargin = 0;
        lp.bottomMargin = 0;
        lp.width = UIUtils.WH()[0];
        lp.height = videoH;


        RelativeLayout.LayoutParams lyCoverParams = (RelativeLayout.LayoutParams) lyCover.getLayoutParams();
        lyCoverParams.addRule(RelativeLayout.BELOW, R.id.id_ly_edit_content);// 子控件相对于控件：imageViewId在其的下面

        //在播放器下方
        lp.addRule(RelativeLayout.BELOW, R.id.id_ly_cover);// 子控件相对于控件：imageViewId在其的下面
        idVideoRy.setLayoutParams(lp);


        RelativeLayout.LayoutParams imgLp = (RelativeLayout.LayoutParams) idPrvBg.getLayoutParams();
        imgLp.width = FrameLayout.LayoutParams.MATCH_PARENT;
        imgLp.height = FrameLayout.LayoutParams.MATCH_PARENT;
        idPrvBg.setLayoutParams(imgLp);
        scrollView.scrollTo(0, 0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(UserMakeTag userMakeTag) {
        setUserMakeTag(userMakeTag);
        if (userMakeTag.equals(UserMakeTag.SETCOVER) || userMakeTag.equals(UserMakeTag.SETBG)) {
            showProgressDialogWithText("");
            // onPause();
            mPresenter.newLoadDocPreview(docInfo.getId() + "");
        } else if (userMakeTag.equals(UserMakeTag.REMOVEWATER)) {
            tvProductTag.setText("高清去水印");
            docInfo.setWatermarkPay(1);
            docInfo.setWatermark(1);
            //showProgressDialogWithText("正在努力去水印");
            //mPresenter.removeWatermark(docInfo.getId() + "");
            mPresenter.newLoadDocPreview(docId);
        } else if (userMakeTag.equals(UserMakeTag.REFRESH)) {
            // T_.showToastReal("刷新.....");
            mPresenter.loadUserDetailInfo();
        }
    }

    public void showBgDialog() {
        Bundle bundle = new Bundle();
        L_.e("afterCreate showBgDialog id :" + docInfo.getId() + "");
        bundle.putString(AppConst.DOCID, docInfo.getId() + "");
        //bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
        bundle.putString(WorkPlatform.TYPE, subType);
        //openActivity(VideobgActivity.class, bundle);
        Intent intent = new Intent(V1_4_VideoPreviewActivity.this, VideobgDialgActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void copyAndNewProductSuccess(String result) {
        gotoMakeVideoActivity(result, WorkPlatform.MOUDLE);
    }

    @Override
    public void getDocStringPreview(String result) {
        gotoMakeVideoActivity(result, WorkPlatform.W0RK);
    }

    /**
     * 增加失败状态 给制作页面
     * <p>
     * 如果失败则先更新在预览
     *
     * @param result
     */
    protected void gotoMakeVideoActivity(String result, String typeModel) {
        Bundle bundle = new Bundle();
        bundle.putString("module", result);
        bundle.putString(WorkPlatform.TYPE, typeModel);
        //todo
        bundle.putInt(AppConst.MAKE_WORK_STATE, MAKE_WORK_STATE);
        openActivity(MakeActivityV1_6.class, bundle);
    }

    protected void gotoCommoninchingVideoBgActivity() {
        Bundle bundle = new Bundle();
        bundle.putInt(IntentCode.INCHING_TYPE, IntentCode.SUB_TYPE_PRODUCE);
        bundle.putInt(IntentCode.TAG, IntentCode.INTENT_VERTICAL_VIDEP);
        bundle.putInt(AppConst.BGID, Integer.valueOf(docInfo.getId()));
        bundle.putString(AppConst.DOCID, docInfo.getId() + "");
        bundle.putString(WorkPlatform.TYPE, subType);
        openActivity(CommoninchingVideoBgActivity.class, bundle);
    }

    /**
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**背景编辑**/
            case R.id.ly_videoframe:
            case R.id.id_ly_edit_bg:
                if (OnMultiClickUtils.isFastClick()) {
                    if (NetUtils.isConnected(getApplication())) {

                        if (docInfo.getWatermark() == 1) {
                            //ActivityUtils.popAllActivityUntillOne(MakeActivity.class);
                            if (isHaveBg) {
                                gotoCommoninchingVideoBgActivity();
                            } else {
                                showBgDialog();
                            }
                        } else {
                            //已经去水印
                            setUserMakeTag(UserMakeTag.SETBG);
                            showUpdateWorkDialog();
                        }
                    } else {
                        T_.showCustomToast("请检查网络");
                    }
                }
                break;
            /**删除背景**/
            case R.id.ly_registrationform:
            case R.id.id_ly_del_bg:
                if (OnMultiClickUtils.isFastClick()) {
                    if (NetUtils.isConnected(getApplication())) {
                        // mPresenter.deleteVideoBg(docInfo.getId() + "");
                        //添加表格
                        Bundle bundle = new Bundle();
                        bundle.putString(AppConst.WEBTYPE, AppConst.TYPE_ADDFORM);
                        bundle.putString(AppConst.DOCID, docInfo.getId() + "");
                        bundle.putString(AppConst.TYPE_ADDFORM_STATE, docInfo.getFormState() + "");
                        Intent intent = new Intent(V1_4_VideoPreviewActivity.this, CommWebActivity.class);
                        //  openActivity(CommWebActivity.class, bundle);
                        intent.putExtras(bundle);
                        // startActivity(intent);
                        startActivityForResult(intent, START_COMMWEBACTIVITY);
                    } else {
                        T_.showCustomToast("请检查网络");
                    }

                }
                break;
            /**左边返回按钮**/
            case R.id.iv_left_bar:
                jugleQuit();
                break;
            /**完成或者修改**/
            case R.id.tv_right_bar:
                if (!OnMultiClickUtils.isFastDoubleClick(R.id.tv_right_bar)) {
                    if (subType != null && subType.equals(WorkPlatform.W0RK)) {
                        if (docInfo.getWatermark() == 1) {
                            mPresenter.getDocString(docInfo.getId() + "");
                        } else {
                            //如果已经去水印  重新拷贝生成
                            setUserMakeTag(UserMakeTag.UPDATE);
                            showUpdateWorkDialog();
                        }
                    } else {
                        sendRemoveThreeLogic();
                    }
                }
                break;
            /**作品名称**/
            case R.id.up_edit:
                break;
            case R.id.id_ly_edit_cover:
                gotoSelectType();
                break;
            /**封面入口**/
            case R.id.id_ly_cover:
                if (docInfo.getWatermark() == 1) {
                    gotoCoverActivity();
                } else {
                    setUserMakeTag(UserMakeTag.SETCOVER);
                    showUpdateWorkDialog();
                }
                break;
            case R.id.id_tv_save_share:
            case R.id.id_tv_save_to_local:
                setUserMakeTag(UserMakeTag.DOWNLOAD);
                saveAndShare();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == START_COMMWEBACTIVITY) {
            int formState = data.getIntExtra(AppConst.TYPE_ADDFORM_STATE, 0);
            L_.e("onActivityResult formState" + formState);
            switch (formState) {
                case 1:
                    lgRegistrationform.setImageResource(R.mipmap.icon_baoming_bg);
                    break;
                case 0:
                    lgRegistrationform.setImageResource(R.mipmap.icon_baoming_bg_un);
                    break;
            }
        }

    }
}
